package com.wzr.login;

import com.wzr.bean.User;
import com.wzr.mapper.UserMapper;
import com.wzr.login.model.LoginChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/kd-pos")
public class LoginController {

	@Autowired
	private UserMapper userMapper;

	@RequestMapping("/login")
	public Map<String, String> login(HttpServletRequest req) {
		String username = req.getParameter("username").trim();
		String password = req.getParameter("password");

		HashMap<String, String> resultMap = new HashMap<>();
		User user = null;
		try {
			user = userMapper.getUserByName(username);
			if (user == null) {
				resultMap.put("ret", "FAIL");
				resultMap.put("description", "用户 '" + username + "' 不存在");
				return resultMap;
			}
			if (LoginChecker.accessCheck(password, user.getSID())) {
				resultMap.put("ret", "SUCCESS");
				resultMap.put("description", "验证通过");
				return resultMap;
			}
			else {
				resultMap.put("ret", "FAIL");
				resultMap.put("description", "密码错误");
				return resultMap;
			}
		} catch (CannotGetJdbcConnectionException e) {
			resultMap.put("ret", "FAIL");
			resultMap.put("description", "数据库连接失败");
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}
}
